package C051;

/**
 * ClassName: C02
 * Package: C051
 * Description:
 *
 * @Author BCXJ
 * @Create 2025/2/28 22:42
 * @Version 1.0
 * @Since 1.0
 */
public class C02 {
    public static void main(String[] args) {
        int[] arr = {2,3,1,2,4,3};
        System.out.println(splitArray(arr, 5));
    }
    public static  int splitArray(int[] nums, int k) {
        int sum = 0;
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
        }
        if(k == 1) {
            return sum;
        }
        int l = 0, r = sum, mid = 0, ans = 0;
        while(l <= r) {
            mid = l + ((r - l) >> 1);
            if(process(nums, mid) > k) {
                l = mid + 1;
            } else {
                ans = mid;
                r = mid - 1;
            }
        }
        return ans;
    }

    private static int process(int[] nums, int mid) {
        int ans = 0;
        int sum = 0;
        for (int i = 0; i < nums.length; i++) {
            if(nums[i] > mid) {
                return Integer.MAX_VALUE;
            }
            sum += nums[i];
            if(sum > mid) {
                ans ++;
                sum = 0;
                i--;
            }
        }
        if(sum != 0) {
            ans ++;
        }
        return ans;
    }


    public static int f(int[] arr, long limit) {
        int parts = 1;
        int sum = 0;
        for (int num : arr) {
            if (num > limit) {
                return Integer.MAX_VALUE;
            }
            if (sum + num > limit) {
                parts++;
                sum = num;
            } else {
                sum += num;
            }
        }
        return parts;
    }

}
